from PyQt5.QtWidgets import QMessageBox
import pymysql
from .login_ui import LoginUI
from ui import MilitaryDetectionSystem

class LoginWindow(LoginUI):
    def __init__(self):
        super().__init__()
        self.setup_connections()
        self.main_system = None  # 添加主窗口实例变量
        
    def setup_connections(self):
        """设置信号连接"""
        self.login_button.clicked.connect(self.login)
        
    def login(self):
        """登录功能"""
        username = self.username_input.text()
        password = self.password_input.text()
        
        if self.verify_credentials(username, password):
            self.open_main_system()
        else:
            QMessageBox.warning(self, "登录失败", "用户名或密码错误！")
            
    def verify_credentials(self, username, password):
        """验证用户凭据"""
        try:
            connection = pymysql.connect(
                host='localhost',
                user='root',
                password='123456',
                database='military',
                charset='utf8mb3',
                cursorclass=pymysql.cursors.DictCursor
            )
            
            with connection.cursor() as cursor:
                sql = "SELECT * FROM users WHERE username = %s AND password = %s"
                cursor.execute(sql, (username, password))
                result = cursor.fetchone()
                
            connection.close()
            return bool(result)
            
        except pymysql.Error as e:
            QMessageBox.critical(self, '数据库错误', str(e))
            return False
            
    def open_main_system(self):
        """打开主系统"""
        QMessageBox.information(self, "登录成功", "欢迎进入智慧战场目标检测系统！")
        self.main_system = MilitaryDetectionSystem()  # 创建主窗口实例
        self.main_system.show()  # 显示主窗口
        self.hide()  # 隐藏登录窗口而不是关闭它 